import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import member from "@src/store/member";
import { parseCategoryRights, parseRechargeAwardRule } from "@src/common/memberCardUtils";
import base from "@src/store/base";
import router from "@src/router";
import dayjs from "dayjs";

Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: member,
    fields: ['expireTime', 'status', 'categoryName', 'cardOrder'],
  }, {
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }],
  properties: {
    availableData: {
      type: Array,
      value: []
    },
    serviceTime: {
      type: String
    }
  },
  data: {
    days: null,
    category: null,
    expireTimeTips: false,
    validPeriod: null,
    categoryRights: [],
  },
  lifetimes: {
    attached: function () {
    }
  },
  observers: {
    'cardOrder,availableData': function (cardOrder, availableData) {
      if (cardOrder && availableData) {
        this.findUpdateCard(availableData);
      }
    },
    'status, expireTime, serviceTime': function (status, expireTime, serviceTime) {
      if (status === 1 && expireTime) {
        let days = dayjs(expireTime).diff(serviceTime, 'day');
        this.setData({ expireTimeTips: days <= 30, days: days })
      } else if (status === 2) {
        this.setData({ expireTimeTips: true, expireTimeShow: dayjs(expireTime).format('YYYY-MM-DD') })
      } else {
        this.setData({ expireTimeTips: false })
      }
    },
  },
  methods: {
    onPullDownRefresh() {
      console.info("onPullDownRefresh")
    },
    findUpdateCard(availableData) {
      for (let card of availableData) {
        if (card.category.cardOrder > this.data.cardOrder) {
          let category = card.category
          let rechargeAward = card.rechargeAward
          let categoryRights = parseCategoryRights(category, rechargeAward).concat(parseRechargeAwardRule(rechargeAward))
          let validPeriod = ""
          if (category.validPeriod === 0) {
            validPeriod = '永久'
          } else {
            validPeriod = `${category.validPeriod}年`
          }
          this.setData({ category, categoryRights, validPeriod })
          return;
        }
        this.setData({ category: null })
      }
    }
  }
})
